package com.cai.seckill.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.cai.seckill.common.exception.GlobalException;
import com.cai.seckill.common.vo.GoodsVo;
import com.cai.seckill.common.vo.RespBean;
import com.cai.seckill.common.vo.RespBeanEnum;
import com.cai.seckill.config.interceptor.AccessLimit;
import com.cai.seckill.pojo.SeckillOrder;
import com.cai.seckill.pojo.SeckillMessage;
import com.cai.seckill.pojo.User;
import com.cai.seckill.service.GoodsService;
import com.cai.seckill.service.OrderService;
import com.cai.seckill.service.SeckillOrderService;
import com.cai.seckill.util.rabbitMQ.MQSender;
import com.wf.captcha.ArithmeticCaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject secKill
 * @Package com.cai.seckill.controller
 * @Author Uli1024
 * @CreaterTime 2022/8/6 22:20
 */
@Controller
@RequestMapping("/seckill")
@Slf4j
public class SeckillController implements InitializingBean {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SeckillOrderService seckillOrderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MQSender mqSender;
    @Autowired
    DefaultRedisScript script;

    //通过内存标记减少redis的访问，原理是存储每种商品是否有库存，减少库存之前就可以先知道是否还有库存
    private Map<Long, Boolean> emptyStockMap = new HashMap<>();

    /**
     * 系统初始化，把商品库存数量加载到Redis
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        List<GoodsVo> list = goodsService.findGoodsVo();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        list.forEach(goodsVo -> {
            redisTemplate.opsForValue().set("seckillGoods:" + goodsVo.getId(), goodsVo.getStockCount());
            //初始化默认每种商品都有库存
            emptyStockMap.put(goodsVo.getId(), false);
        });
    }

    /**
     * 秒杀
     * 没有任何优化 windows QPS：527.0925574530888
     * <p>
     * 使用缓存存储订单和用户，并且防止同一个用户抢两次，采用的措施是innodb行锁和复合索引 windows QPS：978.8566953797964
     * <p>
     * 全部优化之后windows QPS：2851.43997718848
     *
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/{path}/doSeckill", method = RequestMethod.POST)
    @ResponseBody
    public RespBean doSeckill(@PathVariable String path, User user, Long goodsId) {
        //用户没有登陆
        if (user == null) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        //ValueOperations valueOperations = redisTemplate.opsForValue();
        boolean check = orderService.checkPath(user, goodsId, path);
        if (!check) {
            return RespBean.error(RespBeanEnum.REQUEST_ILLEGAL);
        }
        /*以下操作全被MQ优化

        //判断库存
        GoodsVo goodsVo = goodsService.findGoodVoByGoodsId(goodsId);
        if (goodsVo.getStockCount() < 1) {
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //判断是否重复抢购
        //SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>()
        //        .eq("user_id", user.getId())
        //        .eq("goods_id", goodsId));
        Order seckillOrder = (Order) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (seckillOrder != null) {
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }

        Order order = orderService.seckill(user, goodsVo);
        return RespBean.success(order);
*/

        //通过内存标记减少redis的访问
        if (emptyStockMap.get(goodsId)) {
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }

        //判断是否重复抢购
        SeckillOrder seckillOrder =
                (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        if (seckillOrder != null) {
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }

        //预减库存（看afterPropertiesSet方法，那个方法在该类初始化的时候就将商品库存数量加载到Redis）
        //Long stock = valueOperations.decrement("seckillGoods:" + goodsId);
        //使用lua去了
        Long stock = (Long) redisTemplate.execute(script,
                Collections.singletonList("seckillGoods:" + goodsId), Collections.EMPTY_LIST);

        if (stock < 0) {
            //因为是先减再拿到库存数，可能会减得比0小，所以在加回去，
            // 但是现在用了lua或者是redisson锁了，能够保证在自减之前先查询库存量不小于等于0，
            // 而且是原子性操作，不必担心判断有库存但是被别的线程自减之后自己再自减就小于0的情况发生
            //valueOperations.increment("seckillGoods:" + goodsId);

            //没库存了
            emptyStockMap.put(goodsId, true);
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }

        // 请求入队，立即返回排队中
        SeckillMessage seckillMessage = new SeckillMessage(user, goodsId);
        mqSender.sendSeckillMessage(JSONUtil.toJsonStr(seckillMessage));

        //返回0，用户排队中
        return RespBean.success(0);
    }

    /**
     * 获取秒杀结果
     * <p>
     * orderId：成功； -1：失败； 0：排队中
     *
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/getResult", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getResult(User user, Long goodsId) {
        Assert.notNull(user, "用户未登录");

        Long orderId = seckillOrderService.getResult(user, goodsId);
        return RespBean.success(orderId);
    }


    /**
     * 获取秒杀地址
     *
     * @param user
     * @param goodsId
     * @return
     */
    @AccessLimit(second = 5, maxCount = 5, needLogin = true)
    @RequestMapping(value = "/path", method = RequestMethod.GET)
    @ResponseBody
    public RespBean getPath(User user, Long goodsId, String captcha, HttpServletRequest request) {
        if (user == null) {
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        ////方便测试
        //captcha = "0";
        boolean check = orderService.checkCaptcha(user, goodsId, captcha);
        if (!check) {
            return RespBean.error(RespBeanEnum.ERROR_CAPTCHA);
        }
        String str = orderService.createPath(user, goodsId);
        return RespBean.success(str);
    }


    /**
     * 验证码
     *
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void verifyCode(User user, Long goodsId, HttpServletResponse response) {
        if (null == user || goodsId < 0) {
            throw new GlobalException(RespBeanEnum.REQUEST_ILLEGAL);
        }
        // 设置请求头为输出图片类型
        response.setContentType("image/jpg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //生成算数类型验证码，将结果放入redis
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 32, 3);

        redisTemplate.opsForValue().set("captcha:" + user.getId() + ":" + goodsId, captcha.text
                (), 300, TimeUnit.SECONDS);
        try {
            captcha.out(response.getOutputStream());
        } catch (IOException e) {
            log.error("验证码生成失败", e.getMessage());
        }
    }
}
